<template>
  <n-grid cols="1 s:1 m:1 l:4 xl:4 2xl:4" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
        <n-form-item label="账号" path="username">
          <n-input v-model:value="formValue.username" disabled />
        </n-form-item>

        <n-form-item label="昵称" path="nickname">
          <n-input v-model:value="formValue.nickname" placeholder="请输入昵称" />
        </n-form-item>

        <n-form-item label="邮箱" path="email">
          <n-input placeholder="请输入邮箱" v-model:value="formValue.email" />
        </n-form-item>

        <n-form-item label="手机号码" path="mobile">
          <n-input placeholder="请输入联系电话" v-model:value="formValue.mobile" />
        </n-form-item>

        <n-form-item label="性别" path="sex">
          <n-radio-group v-model:value="formValue.sex" name="radiogroup">
            <n-space>
              <n-radio v-for="item in sexList" :key="item.dict_value" :value="item.dict_value">
                {{ item.dict_label }}
              </n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>

        <n-form-item label="个人介绍" path="remark">
          <n-input v-model:value="formValue.remark" type="textarea" placeholder="请输入个人介绍" />
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit">保存基本信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { editUserInfo } from '@/api/system/user';
  import { useUserStore } from '@/store/modules/user';
  import { useDictionary } from '@/hooks/web/useDictionary';

  const sexList = ref<any[]>();
  const userStore = useUserStore();
  const { getDictTypeList } = useDictionary();
  const rules = {
    nickname: {
      required: true,
      message: '请输入昵称',
      trigger: 'blur',
    },
  };
  const formRef: any = ref(null);
  const message = useMessage();

  const userInfo = userStore.getUserInfo;

  const formValue = reactive({
    username: userInfo.username,
    email: userInfo.email,
    mobile: userInfo.mobile,
    nickname: userInfo.nickname,
    remark: userInfo.remark,
    sex: userInfo.sex,
  });

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        editUserInfo(formValue).then(() => {
          message.success('保存成功');
        });
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  onMounted(async () => {
    const res = await getDictTypeList({ dict_type: 'sys_user_sex' });
    sexList.value = res.list;
  });
</script>
